<?php

namespace services\rbac;

use common\components\Service;
use common\models\rbac\Action;
use common\models\rbac\Menu;
use common\models\rbac\Module;
use common\models\rbac\RolePermission;

/**
 * Class RolePermissionService
 * @package services\rbac
 */
class RolePermissionService extends Service
{
    /**
     * 权限信息
     *
     * @param array $condition
     * @return RolePermission|null
     */
    public function findInfo(array $condition = []): ?RolePermission
    {
        $query = RolePermission::find();

        isset($condition['role_id']) && $query->andWhere(['role_id' => $condition['role_id']]);
        isset($condition['permission_id']) && $query->andWhere(['permission_id' => $condition['permission_id']]);
        isset($condition['permission_type']) && $query->andWhere(['permission_type' => $condition['permission_type']]);

        return $query->one();
    }

    /**
     * 获取列表
     *
     * @param array $condition
     * @return array|\yii\db\ActiveRecord[]
     */
    public function findList(array $condition = [])
    {
        $query = RolePermission::find();

        isset($condition['project_id']) && $query->andWhere(['project_id' => $condition['project_id']]);
        isset($condition['role_id']) && $query->andWhere(['role_id' => $condition['role_id']]);
        isset($condition['permission_type']) && $query->andWhere(['permission_type' => $condition['permission_type']]);

        return $query->asArray()->all();
    }

    /**
     * 获取用户菜单列表
     *
     * @param int $roleIds 角色IDs
     * @param int $projectId 项目ID
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getMenuList($roleIds = 0, $projectId = 0)
    {
        if (empty($roleIds)) {
            return [];
        }

        $query = RolePermission::find()->alias('a')->select(['b.*'])
            ->join('INNER JOIN', Menu::tableName().' AS b', 'b.id = a.permission_id')
            ->where([
                'a.permission_type' => RolePermission::PERMISSION_TYPE_MENU,
                // 'a.project_id' => $projectId,
                'b.status' => Menu::STATUS_ENABLE,
            ]);

        $query->andWhere([
            'or',
            ['a.project_id' => $projectId],
            ['a.project_id' => 0],
        ]);

        $query->andWhere(['a.role_id' => $roleIds]);

        return $query->orderBy(['b.sort' => SORT_ASC, 'b.id' => SORT_ASC])->asArray()->all();
    }

    /**
     * 格式化菜单数据
     *
     * @param array $data 查询结果【getMenuList】
     * @param int $pid 菜单parent_menu_id
     * @param int $isSuper 是否超管
     * @return array
     */
    public function menuListFormat(array $data, $pid = 0, int $isSuper = 0)
    {
        $list = [];
        foreach ($data as $row) {
            if ($row['parent_menu_id'] != $pid) {
                continue;
            }
            // 子菜单
            $children = $this->menuListFormat($data, $row['id'], $isSuper);

            // 超管【展示】
            if ($isSuper == 1) {
                if ($row['name'] == '系统设置') {
                    /*$children[] = [
                        'title' => '全局设置',
                        'path' => '/setting/overall',
                        'custom' => 'ivu-icon ivu-icon-ios-build-outline',
                        'children' => [],
                    ];*/

                    $children[] = [
                        'title' => '基础设置',
                        'path' => '/setting/basics',
                        'custom' => 'ivu-icon ivu-icon-ios-cog',
                        'children' => [
                            [
                                'title' => '项目列表',
                                'path' => '/home/setting/basics/project',
                                'custom' => 'ivu-icon ivu-icon-md-grid',
                                'children' => [],
                            ],
                            [
                                'title' => '岗位列表',
                                'path' => '/home/setting/basics/post',
                                'custom' => 'ivu-icon ivu-icon-ios-pulse',
                                'children' => [],
                            ],
                            [
                                'title' => '角色列表',
                                'path' => '/home/setting/basics/role',
                                'custom' => '',
                                'children' => [],
                            ],
                            [
                                'title' => '员工管理',
                                'path' => '/home/setting/basics/personnel',
                                'custom' => 'ivu-icon ivu-icon-md-person',
                                'children' => [],
                            ],
                            [
                                'title' => '病种列表',
                                'path' => '/home/setting/basics/disease',
                                'custom' => 'ivu-icon ivu-icon-ios-ribbon-outline',
                                'children' => [],
                            ],
                            [
                                'title' => '风控类型',
                                'path' => '/home/setting/basics/risk',
                                'custom' => 'ivu-icon ivu-icon-ios-ribbon-outline',
                                'children' => [],
                            ],
                            [
                                'title' => '部位',
                                'path' => '/home/setting/basics/position',
                                'custom' => 'ivu-icon ivu-icon-ios-exit-outline',
                                'children' => [],
                            ],
                            [
                                'title' => '回访状态',
                                'path' => '/home/setting/marketing/returnVisit',
                                'custom' => 'ivu-icon ivu-icon-ios-exit-outline',
                                'children' => [],
                            ],
                            [
                                'title' => '就诊类型',
                                'path' => '/home/setting/marketing/diagnosis',
                                'custom' => 'ivu-icon ivu-icon-ios-exit-outline',
                                'children' => [],
                            ],
                        ],
                    ];
                } else if ($row['name'] == '权限设置') {
                    $children[] = [
                        'title' => '菜单',
                        'path' => '/home/setting/power/menu',
                        'custom' => 'ivu-icon ivu-icon-md-menu',
                        'children' => [],
                    ];

                    $children[] = [
                        'title' => '动作',
                        'path' => '/home/setting/power/power',
                        'custom' => 'ivu-icon ivu-icon-ios-play-outline',
                        'children' => [],
                    ];
                }
            }

            $item = [
                'header' => $row['module_id'],
                'title' => $row['name'],
                'path' => $row['url'],
                'custom' => $row['class_style'],
                'children' => $children,
            ];

            $list[] = $item;
        }

        return $list;
    }

    /**
     * 获取用户动作列表
     *
     * @param int $roleIds 角色IDs
     * @param int $memberId 用户ID
     * @param int $projectId 项目ID
     * @param array $condition 额外条件
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getActionList($roleIds = 0, $projectId = 0, array $condition = [])
    {
        if (empty($roleIds)) {
            return [];
        }

        $query = RolePermission::find()->alias('a')->select(['b.*'])
            ->join('INNER JOIN', Action::tableName().' AS b', 'b.id = a.permission_id')
            ->where([
                'a.permission_type' => RolePermission::PERMISSION_TYPE_ACTION,
                // 'a.project_id' => $projectId,
                'b.status' => Action::STATUS_ENABLE,
            ]);

        $query->andWhere([
            'or',
            ['a.project_id' => $projectId],
            ['a.project_id' => 0],
        ]);

        $query->andWhere(['a.role_id' => $roleIds]);

        if (isset($condition['permission_id'])) {
            $query->andWhere(['permission_id' => $condition['permission_id']]);
        }

        return $query->orderBy(['b.sort' => SORT_ASC, 'b.id' => SORT_ASC])->asArray()->all();
    }

    /**
     * 格式化动作列表
     *
     * @param array $data 查询结果【getActionList】
     * @return array
     */
    public function actionListFormat(array $data)
    {
        $list = [];
        foreach ($data as $row) {
            $list[] = $row['flag'];
        }

        return $list;
    }

    /**
     * 获取用户模块列表
     *
     * @param int $roleIds 角色IDs
     * @param int $memberId 用户ID
     * @param int $projectId 项目ID
     * @param array $condition 额外条件
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getModuleList($roleIds = 0, $projectId = 0, array $condition = [])
    {
        if (empty($roleIds)) {
            return [];
        }

        $query = RolePermission::find()->alias('a')->select(['b.*'])
            ->innerJoin(Module::tableName().' AS b', 'b.id = a.permission_id')
            ->where([
                'a.permission_type' => RolePermission::PERMISSION_TYPE_MODULE,
                // 'a.project_id' => $projectId,
                'b.status' => Module::STATUS_ENABLE,
            ]);

        $query->andWhere([
            'or',
            ['a.project_id' => $projectId],
            ['a.project_id' => 0],
        ]);

        $query->andWhere(['a.role_id' => $roleIds]);

        if (isset($condition['permission_id'])) {
            $query->andWhere(['permission_id' => $condition['permission_id']]);
        }

        return $query->orderBy(['b.sort' => SORT_ASC, 'b.id' => SORT_ASC])->asArray()->all();
    }

    /**
     * 格式化动作列表
     *
     * @param array $data 查询结果【getModuleList】
     * @return array
     */
    public function moduleListFormat(array $data)
    {
        $list = [];
        foreach ($data as $row) {
            $list[] = [
                'name' => $row['id'],
                'title' => $row['name'],
                'path' => $row['url'],
                'icon' => $row['class_style'],
                'hideSider' => false,
            ];
        }

        return $list;
    }
}
